﻿/// <summary>
/// data   :2016-05-04
/// author :fanzhengyong
/// 初始化本地文件的实现（根据版本号最终实现把AB文件拷贝到应用目录）
/// </summary>
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

namespace UEngine
{

    /// <summary>
    /// IEnumerator的限制
    /// （1）不能用枚举参数, 
    /// （2）throw后外面不能catch
    /// </summary>

    public class BundleListData
    {
        public string m_path;
        public int m_versionID;
        public List<string> m_fileList = new List<string>();
    }

    public class InitLocalResLoadingBus
    {

        private bool m_isFinishedParse    = false;
        private bool m_isAllFinished      = false;

        private string m_streamDirRoot;
        private string m_streamDirPath;
        private string m_appDirRoot;
        private string m_appDirPath;
        private Dictionary<string, BundleListData> m_listDirc = new Dictionary<string, BundleListData>();

        private float m_percent = 0.0f;

        public void Work()
        {
#if   UNITY_ANDROID
		    m_streamDirRoot = Application.streamingAssetsPath;
#elif UNITY_IPHONE
            m_streamDirRoot = Application.dataPath + "/Raw/";
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
            m_streamDirRoot = "file://" + Application.streamingAssetsPath;
#endif
            m_streamDirPath = m_streamDirRoot + "/assetlist.bundle";
            Debug.Log(m_streamDirPath);
            BundleListData stramDirData = new BundleListData();
            stramDirData.m_path = m_streamDirPath;
            stramDirData.m_versionID = 0;
            stramDirData.m_fileList = new List<string>();
            m_listDirc.Add(m_streamDirPath, stramDirData);

#if UNITY_ANDROID
		    m_appDirRoot = "file://" + Application.persistentDataPath;
#elif UNITY_IPHONE
            m_appDirRoot = Application.dataPath + "/Raw/";
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
            m_appDirRoot = "file:///" + Application.persistentDataPath;
#endif
            m_appDirPath = m_appDirRoot + "/assetlist.bundle";
            Debug.Log(m_appDirPath);
            BundleListData appDirData = new BundleListData();
            appDirData.m_path = m_streamDirPath;
            appDirData.m_versionID = 0;
            appDirData.m_fileList = new List<string>();
            m_listDirc.Add(m_appDirPath, appDirData);

            Main.instance.StartCoroutine(ParseTask());
        }

        public void Update()
        {
            if (!m_isAllFinished)
            {
                if (m_isFinishedParse)
                {
                    Main.instance.StartCoroutine(CopyBundleFileTask());
                    m_isAllFinished = true;
                }
            }
        }

        private IEnumerator ParseTask()
        {

            try
            {
                Main.instance.StartCoroutine(ParseListTask(m_streamDirPath));
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            try
            {
                Main.instance.StartCoroutine(ParseListTask(m_appDirPath));
            }
            catch (Exception e)
            {
                Debug.Log(e.Message);

            }

            yield return null;

        }

        private IEnumerator CopyBundleFileTask()
        {
            bool retCode = false;
            //DebugHelper.ErrorMessage(m_listDirc[m_appDirPath].m_versionID.ToString());
            Debug.Log(m_listDirc[m_streamDirPath].m_versionID);
            Debug.Log(m_listDirc[m_appDirPath].m_versionID);
            string sourPath = null;
            string destPath = null;
            if (m_listDirc[m_streamDirPath].m_versionID > m_listDirc[m_appDirPath].m_versionID)
            {
                for (int i = 0; i < m_listDirc[m_streamDirPath].m_fileList.Count; i++)
                {
                    sourPath = m_streamDirRoot + "/" + m_listDirc[m_streamDirPath].m_fileList[i];
                    destPath = Application.persistentDataPath + "/" + m_listDirc[m_streamDirPath].m_fileList[i];
                    //DebugHelper.ErrorMessage(sourPath);
                    WWW www = new WWW(sourPath);
                    //Debug.Log(sourPath);
                    //Debug.Log(destPath);
                    yield return www;
                    do
                    {
                        if (www.error != null)
                        {
                            DebugHelper.ErrorMessage(www.error);
                            break;
                        }
                        if (www.isDone)
                        {
                            //DebugHelper.ErrorMessage(string.Format("create {0}", destPath));
                            retCode = FileHelper.CreateAssetbundleFile(destPath, www.bytes);
                            if (!retCode)
                            {
                                DebugHelper.ErrorMessage(string.Format("create {0} error", destPath));
                                break;
                            }
                        }


                    } while (false);

                    if (www != null)
                    {
                        www.Dispose();
                    }
                    m_percent = i / m_listDirc[m_streamDirPath].m_fileList.Count;
                    GameEventManager.Instance().PushEvent(
                        (int)EPREGAMEEVENTCODE.INITLOCALRES_COPY_BUNDLE_PERCENT, m_percent);
                }
            }

            m_percent = 1.0f;
            GameEventManager.Instance().PushEvent(
                (int)EPREGAMEEVENTCODE.INITLOCALRES_COPY_BUNDLE_PERCENT, m_percent);
            GameEventManager.Instance().PushEvent(
                (int)EPREGAMEEVENTCODE.INITLOCALRES_COPY_BUNDLE_FINISHED);
        }

        public IEnumerator ParseListTask(string path)
        {
            bool retCode = false;
            bool result  = false;

            if (!StringHelper.IsValidString(path))
            {
                DebugHelper.ErrorMessage("param error");
                //throw new Exception("param error");
            }

            BundleListData bundleListData = null;
            if (m_listDirc.ContainsKey(path))
            {
                bundleListData = m_listDirc[path];
            }

            WWW www = new WWW(path);
            yield return www;
            AssetBundle assetbundle = null;
            TextAsset textAsset = null;

            do
            {
                if (www.error != null)
                {
                    //if (StringHelper.StringCompare(path, m_streamDirPath))
                    //{
                    //    DebugHelper.ErrorMessage(www.error);
                    //}

                    //throw new Exception(www.error);
                    break;
                }

                if (www.isDone)
                {
                    //if (StringHelper.StringCompare(path, m_streamDirPath))
                    //{
                    //    DebugHelper.ErrorMessage("www.isDone");
                    //}
                    assetbundle = www.assetBundle;
                    if (assetbundle == null)
                    {
                        DebugHelper.ErrorMessage("assetbundle == null");
                        //throw new Exception("assetbundle == null");
                        break;
                    }

                    textAsset = assetbundle.LoadAsset("assetlist", typeof(TextAsset)) as TextAsset;
                    if (textAsset == null)
                    {
                        DebugHelper.ErrorMessage("textAsset == null");
                        Debug.Log("textAsset == null");
                        break;
                    }

                    int tempVersionID = 0;
                    Debug.Log(textAsset.text);
                    using (StringReader stringReader = new StringReader(textAsset.text))
                    {
                        //第一行是版本号
                        string firstLine = stringReader.ReadLine();
                        Debug.Log(firstLine);
                        retCode = StringHelper.String2Int32(firstLine, ref tempVersionID);
                        if (retCode)
                        {
                            bundleListData.m_versionID = tempVersionID;
                            result = true;
                        }

                        //第二行开始都是bundle文件名
                        string bundleFileName = null;
                        while ((bundleFileName = stringReader.ReadLine()) != null)
                        {
                            bundleListData.m_fileList.Add(bundleFileName);
                        }
                    }
                }

            } while (false);

            if (assetbundle != null)
            {
                assetbundle.Unload(false);
            }

            if (textAsset != null)
            {
                GameObject.DestroyImmediate(textAsset, true);
            }

            if (www != null)
            {
                www.Dispose();
            }

            if (StringHelper.StringCompare(m_appDirPath, path))
            {
                m_isFinishedParse = true;
            }
        }
    }

}
